package net.xdclass.controller;

import net.xdclass.domain.Video;
import net.xdclass.domain.VideoOrder;
import net.xdclass.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

/**
 * @description: 订单控制器
 * @author: Yz
 * @create: 2020-11-10 14:17
 **/
@RestController
@RequestMapping("api/v1/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private VideoService videoService;

    @GetMapping("/save")
    public Object save(int videoId){
        //Video video = restTemplate.getForObject("http://localhost:9000/api/v1/video/find_by_id?videoId=" + videoId, Video.class);

        //List<ServiceInstance> list = discoveryClient.getInstances("xdclass-video-service");
        //ServiceInstance serviceInstance = list.get(0);
        //Video video = restTemplate.getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/api/v1/video/find_by_id?videoId=" + videoId, Video.class);
        //Video video = restTemplate.getForObject("http://xdclass-video-service/api/v1/video/find_by_id?videoId=" + videoId, Video.class);
        Video video = videoService.findById(videoId);
        VideoOrder videoOrder = new VideoOrder();
        BeanUtils.copyProperties(video,videoOrder);
        videoOrder.setVideoTitle(video.getTitle());
        return videoOrder;
    }

    /**
     * 测试feign调用 使用post方式传输对象
     * @param video
     * @return
     */
    /*@GetMapping("/save")
    public Object save(@RequestBody Video video){
        int rows = videoService.save(video);
        HashMap<String,Object> map = new HashMap<>();
        map.put("rows", rows);
        return map;
    }*/


    int temp = 0;

    /**
     * 测试sentinel 并发线程数限流
     * @return
     */
    @GetMapping("/list")
    public Object list(){
        /*try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        temp++;
        if (temp%3==0){
            throw new RuntimeException();
        }

        HashMap<String,Object> map = new HashMap<>();
        map.put("title1", "AlibabaCloud微服务专题");
        map.put("title2", "面试专题");
        return map;
    }
}
